<template>
  <!-- 上传组件 -->

  <div class="file-upload" v-if="isFile">
    <el-upload
      v-model="imgUrl"
      class="single-uploader-file"
      :show-file-list="false"
      list-type="picture-card"
      :before-upload="handleBeforeUpload"
      :http-request="uploadFile"
      style="display: block;width: 120px;"
    >上传文件
    </el-upload>
    <div class="clearfix"></div>
    <div style="width: 100%;" v-if="fileName">{{ fileName }}</div>
  </div>

  <el-upload
    v-model="imgUrl"
    class="single-uploader"
    :show-file-list="false"
    list-type="picture-card"
    :before-upload="handleBeforeUpload"
    :http-request="uploadFile"
    v-else
  >
    <img v-if="imgUrl" :src="defaultSettings.imgDomain + imgUrl" class="single-uploader__image"/>
    <el-icon v-else class="single-uploader__icon">
      <i-ep-plus/>
    </el-icon>
  </el-upload>
</template>

<script setup lang="ts">
import {UploadRawFile, UploadRequestOptions} from "element-plus";
import {uploadFileApi} from "@/api/file";
import defaultSettings from "@/settings";

const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  fkey: {
    type: String,
    default: "",
  }
});

// 判断是否是文件
const isFile = ref(false);
const fileName = ref("");
if (['cert_path', 'key_path'].indexOf(props.fkey) != -1) {
  isFile.value = true;
}

const emit = defineEmits(["update:modelValue", 'uploadSucess']);
const imgUrl = useVModel(props, "modelValue", emit);

/**
 * 自定义图片上传
 *
 * @param options
 */
async function uploadFile(options: UploadRequestOptions): Promise<any> {
  const {data: fileInfo} = await uploadFileApi(options.file);
  fileName.value = fileInfo.name;
  imgUrl.value = fileInfo.path;
  emit("uploadSucess", {value: fileInfo.path, name: props.fkey || ""})
}

/**
 * 限制用户上传文件的格式和大小
 */
function handleBeforeUpload(file: UploadRawFile) {
  if (file.size > 2 * 1048 * 1048) {
    ElMessage.warning("上传图片不能大于2M");
    return false;
  }
  return true;
}
</script>

<style scoped lang="scss">

.single-uploader-file {
  height: 45px;
  width: 120px;
}

.file-upload :deep(.el-upload--picture-card) {
  --el-upload-picture-card-size: auto !important;
  height: 40px;
  width: 100%;
  background: var(--el-color-primary);
  color: #fff;
  //font-size: 16px;
  border: 0px;
}

.single-uploader {
  overflow: hidden;
  cursor: pointer;
  border: 1px var(--el-border-color) solid;
  border-radius: 6px;

  &:hover {
    border-color: var(--el-color-primary);
  }

  &__image {
    display: block;
    width: 178px;
    height: 178px;
  }

  &___icon {
    width: 178px;
    height: 178px;
    font-size: 28px;
    color: #8c939d;
    text-align: center;
  }
}
</style>
